<template>
  <div class="join-addEdit">
    <el-dialog :append-to-body="true" :title="title" v-model="show" @close="cancelFun" destroy-on-close>
      <el-form :model="form" ref="formRef" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="名称:" prop="name">
          <el-input type="text" placeholder="请输入内容" size="large" v-model="form.name" maxlength="50" show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelFun" size="large">取消</el-button>
          <el-button type="primary" @click="confirmFun" size="large">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { computed, onMounted, onUnmounted, ref, watch, defineEmits, reactive } from 'vue'
import {
  editShujiType,
  addShujiType
} from '@api/bookType'
import { ElMessage } from 'element-plus'

const props = defineProps({
  status: {
    type: String,
    default: null
  },
  show: {
    type: Boolean,
    default: null
  },
  addEditData: {
    type: Object,
    default: {
      id: '',
      name: ''
    }
  }
})

const formRef = ref()

const form = ref({
  id: '',
  name: ''
})

const rules = reactive({
  name: [{ required: true, message: '书籍类型名称不能为空!', trigger: 'blur' }],
  phone: [
    {
      required: true,
      validator: (rule, value, callback) => {
        value = form.value.phone
        if (!value) {
          callback(new Error('电话不能为空!'))
        } else if (!/^1[3|4|5|7|8]\d{9}$/.test(value)) {
          callback(new Error('请输入正确的电话号码!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

const emit = defineEmits(['hide-addEdit'])

const title = computed(() => {
  return props.status == 'add' ? '添加书籍类型' : '编辑书籍类型'
})

function confirmFun() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let res = '';
      let { id, name } = form.value
      if (props.status == 'add') {
        res = await addShujiType({ name: name })
      } else if (props.status == 'edit') {
        res = await editShujiType({ id, name: name })
      }

      if (res.code == 200) {
        ElMessage({
          message: '操作成功!',
          type: 'success',
        })
        emit('hide-addEdit', props.status)
      }

    }
  })
}

function cancelFun() {
  emit('hide-addEdit', 'cancel')
}

watch(
  () => props.addEditData,
  (newValue, oldValue) => {
    form.value.id = newValue.id
    form.value.name = newValue.name
  },
  { deep: true }
)
</script>
<style lang="scss" scoped>
.news-addEdit {}
</style>
